package com.hooview.api.controller;

import com.github.pagehelper.Page;
import com.hooview.api.entity.*;
import com.hooview.api.service.*;
import com.hooview.common.utils.AjaxMsg;
import com.hooview.common.utils.ValidUtil;
import com.hooview.contants.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.GET;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * banner表
 *
 * @author lee
 * @email
 * @date 2018-01-19 09:34:44
 */
@RestController
public class NewsController {
    @Autowired
    private NewsService newsService;
    @Autowired
    private LikesService likesService;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private UserService userService;
    @Autowired
    private DailyCountService dailyCountService;
    @Autowired
    private ReadHistoryService readHistoryService;
    @Autowired
    private CollectionsService collectionsService;
    @Autowired
    private FollowsService followsService;
    @Autowired
    private ProfitRecordService profitRecordService;

    /**
     * news 分页
     */
    @RequestMapping(value = "/api/news/queryNews", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg list(int channelId, int pageSize, int maxId, String keyWord, String uid) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String, Object> params = new HashMap();

        if (!ValidUtil.isEmpty(channelId)) {
            Page<Map<String, Object>> list = new Page<>();
            //查询关注作者的文章列表
            if (Constants.CHANNEL_01.equals(channelId)) {
                if (!ValidUtil.isEmpty(uid)) {
                    params.put("pageSize", pageSize);
                    params.put("maxId", maxId);
                    params.put("userId", uid);
                    params.put("keyWord", keyWord);
                    params.put("status", Constants.NEWS_STATUS_ONLINE);
                    list = newsService.findFollowMapByPage(params);
                }
            } else {
                params.put("channelId", channelId);
                params.put("pageSize", pageSize);
                params.put("maxId", maxId);
                params.put("userId", uid);
                params.put("keyWord", keyWord);
                params.put("status", Constants.NEWS_STATUS_ONLINE);
                list = newsService.findMapByPage(params);
            }

            ajaxMsg.setDatas(list);
            ajaxMsg.setCode(AjaxMsg.SUCCESS);
        } else {
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("获取数据失败，请检查参数");
        }

        return ajaxMsg;
    }


    /**
     * news 详细
     */
    @RequestMapping(value = "/api/news/queryNewsDetail", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg queryNewsById(Integer id, String uid) {
        Map<String, Object> params = new HashMap();
        params.put("userId", uid);
        params.put("id", id);
        Map news = newsService.selectMapByPrimaryKey(params);
        String content = news.get("content").toString();
        String style = "<style>*{width: auto !important;max-width: 100% !important;box-sizing: border-box !important;}</style>";
        content = style + content;
        news.put("content",content);
        return new AjaxMsg(news);
    }

    /**
     * news 新消息数量
     */
    @RequestMapping(value = "/api/news/queryNewsCount", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg queryNewsCount(Integer newsId, int channelId) {
        Map<String, Object> map = new HashMap();
        map.put("newsId", newsId);
        map.put("channelId", channelId);
        map.put("status", Constants.NEWS_STATUS_ONLINE);
        Integer count = newsService.queryNewsCount(map);
        return new AjaxMsg(count);
    }


    /**
     * news 收藏
     */
    @RequestMapping(value = "/api/news/queryCollections", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg collections(int pageSize, int maxId, String uid) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String, Object> params = new HashMap();
        if (ValidUtil.isEmpty(uid)) {
            ajaxMsg.setMessage("用户ID不能为空");
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            return ajaxMsg;
        }
        Page<Map<String, Object>> list;
        params.put("pageSize", pageSize);
        params.put("maxId", maxId);
        params.put("userId", uid);
        params.put("status", Constants.NEWS_STATUS_ONLINE);
        list = newsService.queryCollectionsByPage(params);

        ajaxMsg.setDatas(list);
        ajaxMsg.setCode(AjaxMsg.SUCCESS);
        return ajaxMsg;
    }

    /**
     * news 历史
     */
    @RequestMapping(value = "/api/news/queryHistories", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg histories(int pageSize, int maxId, String uid) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String, Object> params = new HashMap();
        if (ValidUtil.isEmpty(uid)) {
            ajaxMsg.setMessage("用户ID不能为空");
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            return ajaxMsg;
        }
        Page<Map<String, Object>> list;
        params.put("pageSize", pageSize);
        params.put("maxId", maxId);
        params.put("userId", uid);
        params.put("status", Constants.NEWS_STATUS_ONLINE);
        list = newsService.queryHistoriesByPage(params);

        ajaxMsg.setDatas(list);
        ajaxMsg.setCode(AjaxMsg.SUCCESS);
        return ajaxMsg;
    }

    /**
     * news 历史
     */
    @RequestMapping(value = "/api/news/queryHistoriesByPageNo", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg queryHistoriesByPageNo(int pageSize, int pageNo, String uid) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String, Object> params = new HashMap();
        if (ValidUtil.isEmpty(uid)) {
            ajaxMsg.setMessage("用户ID不能为空");
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            return ajaxMsg;
        }
        Page<Map<String, Object>> list;
        params.put("pageSize", pageSize);
        params.put("pageNo", pageNo);
        params.put("userId", uid);
        params.put("status", Constants.NEWS_STATUS_ONLINE);
        list = newsService.queryHistoriesByPageNo(params);

        ajaxMsg.setDatas(list);
        ajaxMsg.setCode(AjaxMsg.SUCCESS);
        return ajaxMsg;
    }

    /**
     * news 推荐
     */
    @RequestMapping(value = "/api/news/recommends", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg recommends(int pageSize, int maxId, Integer newsId) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String, Object> params = new HashMap();
        if (ValidUtil.isEmpty(newsId)) {
            ajaxMsg.setMessage("用户ID不能为空");
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            return ajaxMsg;
        }
        Page<Map<String, Object>> list;
        params.put("pageSize", pageSize);
        params.put("maxId", maxId);
        News news = newsService.selectByPrimaryKey(newsId);
        params.put("channelId", news.getChannelId());
        params.put("tag", news.getTag().split(","));
        params.put("status", Constants.NEWS_STATUS_ONLINE);
        list = newsService.queryRecommendsByPage(params);

        ajaxMsg.setDatas(list);
        ajaxMsg.setCode(AjaxMsg.SUCCESS);
        return ajaxMsg;
    }

    /**
     * news 创建人
     */
    @RequestMapping(value = "/api/news/queryAuthorByPage", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg queryAuthorByPage(int pageSize, int maxId, String authorId) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String, Object> params = new HashMap();
        if (ValidUtil.isEmpty(authorId)) {
            ajaxMsg.setMessage("文章作者ID不能为空");
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            return ajaxMsg;
        }
        Page<Map<String, Object>> list;
        params.put("pageSize", pageSize);
        params.put("maxId", maxId);
        params.put("userId", authorId);
        params.put("status", Constants.NEWS_STATUS_ONLINE);
        list = newsService.queryAuthorByPage(params);

        ajaxMsg.setDatas(list);
        ajaxMsg.setCode(AjaxMsg.SUCCESS);
        return ajaxMsg;
    }

    /**
     * news 阅读 收藏 关注 点赞
     */
    @RequestMapping(value = "/api/news/operat", method = RequestMethod.POST)
    public AjaxMsg operatNews(@RequestParam(required = false) String uid, @RequestParam(required = false) Integer newsId, String operatType, @RequestParam(required = false) String authorId) {
        if (ValidUtil.isEmpty(operatType))
            return new AjaxMsg("500", "请求必要参数不能为空!");
        User user = null;
        if (!ValidUtil.isEmpty(uid)) {
            user = userService.queryById(uid);
        }

        //关注
        if (operatType.equals(Constants.NEWS_OPREAT_FOLLOW) || operatType.equals(Constants.NEWS_OPREAT_CANCEL_FOLLOW)) {
            if (ValidUtil.isEmpty(authorId))
                return new AjaxMsg("500", "作者Id不能为空!");
            if (user == null)
                return new AjaxMsg("500", "用户不存在!");
            User author = userService.queryById(authorId);
            if (author == null)
                return new AjaxMsg("500", "关注作者不存在!");
            if (operatType.equals(Constants.NEWS_OPREAT_FOLLOW))
                return followAuthor(user, author);
            if (operatType.equals(Constants.NEWS_OPREAT_CANCEL_FOLLOW))
                return cancelFollowAuthor(user, author);
        }

        News news = newsService.selectByPrimaryKey(newsId);
        if (news == null)
            return new AjaxMsg("500", "文章并不存在!");
        switch (operatType) {
            case Constants.NEWS_OPREAT_READ:
                return readNews(user, news);
            case Constants.NEWS_OPREAT_COLLECT:
                return collectNews(user, news);
            case Constants.NEWS_OPREAT_CANCEL_COLLECT:
                return cancelCollectNews(user, news);
            case Constants.NEWS_OPREAT_SUPPORT:
                return suppOrBoycNews(user, news, Constants.NEWS_SUPPORT);
            case Constants.NEWS_OPREAT_BOYCOTT:
                return suppOrBoycNews(user, news, Constants.NEWS_BOYCOTT);
        }
        return new AjaxMsg();
    }

    //利好 或 利空
    private AjaxMsg suppOrBoycNews(User user, News news, String type) {
        if (user == null) return new AjaxMsg("500", "用户不存在！");
        Likes likes = likesService.selectByUserIdAndNewsId(user.getId(), news.getId());
        if (likes != null)
            return new AjaxMsg("500", "文章已经评价!");
        likesService.insert(user.getId(), news.getId(), type);

        DailyCount dailyCount = dailyCountService.selectToday(user.getId());
        Integer suppBoycAmount = null;
        if (dailyCount != null)
            suppBoycAmount = dailyCount.getSuppBoycAmount();

        if (Constants.NEWS_SUPPORT.equals(type)) {
            news.setSupportAmount(news.getSupportAmount() + 1);
            newsService.updateByPrimaryKeySelective(news);
            //收益
            if (suppBoycAmount != null && suppBoycAmount >= 9)
                return new AjaxMsg();
            profitRecordService.getProfit(user.getId(), Constants.PROFIT_SUPPORT, news.getId());
        }
        if (Constants.NEWS_BOYCOTT.equals(type)) {
            news.setBoycottAmount(news.getBoycottAmount() + 1);
            newsService.updateByPrimaryKeySelective(news);
            //收益
            if (suppBoycAmount != null && suppBoycAmount >= 9)
                return new AjaxMsg();
            profitRecordService.getProfit(user.getId(), Constants.PROFIT_BOYCOTT, news.getId());
        }

        return new AjaxMsg();
    }

    //取消关注
    private AjaxMsg cancelFollowAuthor(User user, User author) {
        if (user == null) return new AjaxMsg("500", "用户不存在！");
        Follows follows = followsService.selectByUidAndAutorId(user.getId(), author.getId());
        if (follows == null)
            return new AjaxMsg("500", "取消关注作者不存在！");
        followsService.deleteById(follows.getId());
        return new AjaxMsg();
    }

    //关注作者
    private AjaxMsg followAuthor(User user, User author) {
        if (user == null) return new AjaxMsg("500", "用户不存在！");
        Follows follow = followsService.selectByUidAndAutorId(user.getId(), author.getId());
        if (follow != null)
            return new AjaxMsg("500", "该作者已被关注!");
        followsService.insert(user.getId(), author.getId());
        return new AjaxMsg();
    }

    //取消收藏
    private AjaxMsg cancelCollectNews(User user, News news) {
        if (user == null) return new AjaxMsg("500", "用户不存在！");
        Collections collection = collectionsService.selectByUidAndNewsId(user.getId(), news.getId());
        if (collection == null)
            return new AjaxMsg("500", "文章并未收藏!");
        collectionsService.deleteById(collection.getId());
        return new AjaxMsg();
    }

    //收藏文章
    private AjaxMsg collectNews(User user, News news) {
        if (user == null) return new AjaxMsg("500", "用户不存在！");
        Collections collection = collectionsService.selectByUidAndNewsId(user.getId(), news.getId());
        if (collection != null)
            return new AjaxMsg("500", "文章已被收藏!");
        collectionsService.insert(user.getId(), news.getId());
        return new AjaxMsg();
    }

    //阅读文章
    private AjaxMsg readNews(User user, News news) {
        //阅读量
        news.setReadAmount(news.getReadAmount() + 1);
        newsService.updateByPrimaryKeySelective(news);
        if (user != null && news.getChannelId() != 7 && news.getChannelId() != 1) {
            //增加历史
            ReadHistory readHistory = readHistoryService.selectByNewsIdAndUid(news.getId(), user.getId());
            if (readHistory != null)
                readHistoryService.deleteById(readHistory.getId());
            readHistoryService.insert(user.getId(), news.getId());
        }
        return new AjaxMsg();
    }


    /**
     * news 是否审核
     */
    @RequestMapping(value = "/api/check", method = RequestMethod.GET)
    @ResponseBody
    public AjaxMsg check() {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map result = new HashMap();
        List<Dictionary> dictionaryList = dictionaryService.getDicByKeyNo(Constants.IOS_CHECK);
        if (!ValidUtil.isEmpty(dictionaryList)) {
            String check = dictionaryList.get(0).getKeyValue();
            result.put("checked", check);
        }
        List<Dictionary> dictionaryList2 = dictionaryService.getDicByKeyNo(Constants.IOS_VERSION);
        if (!ValidUtil.isEmpty(dictionaryList2)) {
            String version = dictionaryList2.get(0).getKeyValue();
            result.put("version", version);
        }
        ajaxMsg.setDatas(result);

        ajaxMsg.setCode(AjaxMsg.SUCCESS);
        return ajaxMsg;
    }

    @PostMapping("/api/news/search")
    @ResponseBody
    public AjaxMsg search(String keyword,@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "10") Integer pageSize){

        List<Map<String,Object>> res = newsService.findByKeyword(keyword,pageNum,pageSize);
        return new AjaxMsg(res);
    }

    @GetMapping("/api/news/recommendAndNextNews")
    @ResponseBody
    public AjaxMsg recommendAndNextNews(Integer currentId){
        Map<String,Object> nextNews = newsService.findNextNews(currentId);
        List<Map<String, Object>> recommendNews = newsService.findRecommendNews(currentId);
        Map res = new HashMap();
        res.put("nextNews",nextNews);
        res.put("recommendNews",recommendNews);
        return new AjaxMsg(res);
    }

}
